//
//  JobDetailService.swift
//  ezyform
//
//  Created by MoennigQ on 16/5/18.
//  Copyright © 2018 Client.Solution Pty Ltd. All rights reserved.
//

import UIKit
import SwiftyJSON
import HandyJSON
import Alamofire

class JobDetailService: BaseService {
    //MARK: - 获取detail信息
    //cacheDataFirstFlag = true表示需要先获取cachedata在请求网络
    func getInstallationsDetail(cacheFlag: Bool = false){
        let alRequest = ALRequest.init(mainURL: APIConfig.getRequestAPIForV2(APIConfig.InstallationDetailAPI,id: JobDetailModelHelper.shared.jobDetailModel.id), method: .get, headers: RequestConstant.AuthTokenParam, paramDict: nil, successBlock: {(obj, _) -> Void in
            if let responseData = obj as? [String : Any], let data = PVDDetailModel.deserialize(from: responseData){
                JobDetailModelHelper.shared.jobDetailModel.copyAllValuesOfModel(data)
                APPConfig.loginInfo.signatureInfoModel.onlineStatementPVDDetail = responseData
                self.returnBlock(obj, nil)
            }else{
                self.errorBlock?("", "Convert response to PVDDetailModel faild")
            }
            
        }) {(code, obj) -> Void in
            self.errorBlock?(code, obj)
        }
        alRequest.startRequest(cacheFlag: cacheFlag)
        
    }
    //MARK: - panel spv验证结果刷新
    func getPanelNumberListForSpv(){
        
        let alRequest = ALRequest.init(mainURL: APIConfig.getRequestAPIForV2(APIConfig.GetPanelNumbersAPI,id: JobDetailModelHelper.shared.jobDetailModel.id), method: .get, headers: RequestConstant.AuthTokenParam, paramDict: nil, successBlock: {(obj, _) -> Void in
            
            let json = JSON(obj!)
            
            self.returnBlock(json.rawString(), nil)
            
        }) {(code, obj) -> Void in
            self.errorBlock?(code, obj)
        }
        alRequest.startRequest()
    }
    //MARK: - 上传签名
    func uploadSignatures(_ model: SignatureImageDBModel){
        let urlStr = APIConfig.getRequestAPIForV2(APIConfig.UploadSignaturesAPI)
        netmanagerForUpload.upload(multipartFormData: {(formData) in
            
            //1.installer signature
            if model.signature_type == SignatureType.Installer{
                let toData = Data(referencing: model.image_data!)
                formData.append(toData, withName: "installer_signed_signature", fileName: model.signature_type.rawValue + APPConfig.ImageSuffix, mimeType: "image/png")
                
                formData.append(model.signed_at.data(using: String.Encoding.utf8, allowLossyConversion: false)!, withName: "installer_signed_at")
                //经纬度
                if let latitude = model.installer_signature_latitude {
                    formData.append("\(latitude)".data(using: String.Encoding.utf8, allowLossyConversion: false)!, withName: "installer_signature_latitude")
                }
                if let longitude = model.installer_signature_longitude {
                    formData.append("\(longitude)".data(using: String.Encoding.utf8, allowLossyConversion: false)!, withName: "installer_signature_longitude")
                }
                //design type,
                if model.installer_statement_design_type != ""{
                    formData.append(model.installer_statement_design_type.data(using: String.Encoding.utf8, allowLossyConversion: false)!, withName: "design_type")
                }
                if model.installer_statement_duty_type != ""{
                    formData.append(model.installer_statement_duty_type.data(using: String.Encoding.utf8, allowLossyConversion: false)!, withName: "on_site_duties")
                }
                //installer 协议版本,此版本号由老袁后台根据版本号3.5.7和is_new_stc_form控制为4，其他还是为3
                //formData.append("3".data(using: String.Encoding.utf8, allowLossyConversion: false)!, withName: "installer_declaration_version")
                //协议自拍照
                if let data = model.installer_agree_selfie {
                    formData.append(Data(referencing: data), withName: "installer_agree_selfie", fileName: "installer_agree_selfie" + APPConfig.ImageSuffix, mimeType: "image/png")
                }
                
                //签名自拍照
                if let data = model.installer_signature_selfie{
                    formData.append(Data(referencing: data), withName: "installer_signature_selfie", fileName: "installer_signature_selfie" + APPConfig.ImageSuffix, mimeType: "image/png")
                }
            }
            //2.designer
            if model.signature_type == SignatureType.Designer{
                let toData = Data(referencing: model.image_data!)
                formData.append(toData, withName: "designer_signed_signature", fileName: model.signature_type.rawValue + APPConfig.ImageSuffix, mimeType: "image/png")
                
                formData.append(model.signed_at.data(using: String.Encoding.utf8, allowLossyConversion: false)!, withName: "designer_signed_at")
                
            }
            //3.owner
            if model.signature_type == SignatureType.Owner{
                
                let toData = Data(referencing: model.image_data!)
                
                formData.append(toData, withName: "owner_signed_signature", fileName: model.signature_type.rawValue + APPConfig.ImageSuffix, mimeType: "image/png")
                formData.append(model.signed_at.data(using: String.Encoding.utf8, allowLossyConversion: false)!, withName: "owner_signed_at")
                //
                if model.print_name != "" {
                    formData.append(model.print_name.data(using: String.Encoding.utf8, allowLossyConversion: false)!, withName: "owner_signed_name")
                }
                //第一部分协议版本
                if model.owner_mandatory_declaration_version != ""{
                    formData.append(model.owner_mandatory_declaration_version.data(using: String.Encoding.utf8, allowLossyConversion: false)!, withName: "owner_declaration_version")
                }
                //第一部分新协议
                if model.owner_financial_incentive != ""{
                    formData.append(model.owner_financial_incentive.data(using: String.Encoding.utf8, allowLossyConversion: false)!, withName: "financial_incentive")
                }
                //第二部分协议版本
                formData.append("2".data(using: String.Encoding.utf8, allowLossyConversion: false)!, withName: "owner_onsite_statement_version")
                //满意度协议条款版本，目前只有
                let firstFormVersion = model.owner_aussolarco_satisfactory_version
                formData.append(firstFormVersion.data(using: String.Encoding.utf8, allowLossyConversion: false)!, withName: "owner_aussolarco_satisfactory_version")
                let secFormVersion = model.owner_satisfaction_completion_version
                formData.append(secFormVersion.data(using: String.Encoding.utf8, allowLossyConversion: false)!, withName: "owner_satisfaction_completion_version")
                //协议勾选数据
                if model.physically_attended != ""  {
                    formData.append(model.physically_attended.data(using: String.Encoding.utf8, allowLossyConversion: false)!, withName: "physically_attended")
                }
                //签名自拍照
                if let data = model.owner_signature_selfie{
                    formData.append(Data(referencing: data), withName: "owner_signature_selfie", fileName: "owner_signature_selfie" + APPConfig.ImageSuffix, mimeType: "image/png")
                }
            }
            //4.witness
            if model.signature_type == SignatureType.Witness{
                
                let toData = Data(referencing: model.image_data!)
                
                formData.append(toData, withName: "witness_signed_signature", fileName: model.signature_type.rawValue + APPConfig.ImageSuffix, mimeType: "image/png")
                
                if model.print_name != "" {
                    formData.append(model.print_name.data(using: String.Encoding.utf8, allowLossyConversion: false)!, withName: "witness_signed_name")
                }
                formData.append(model.signed_at.data(using: String.Encoding.utf8, allowLossyConversion: false)!, withName: "witness_signed_at")
            }
            
            //pvd id
            formData.append(model.pvd_id.data(using: String.Encoding.utf8, allowLossyConversion: false)!, withName: "pvd_id")
            //2022-04-01之后的job，四个签名，和协议相关的字段
            if model.statement_input_param_all != ""{
                formData.append(model.statement_input_param_all.data(using: String.Encoding.utf8, allowLossyConversion: false)!, withName: "statement_input_param_all")
            }
            
        }, to: urlStr, method: HTTPMethod.put, headers: RequestConstant.AuthTokenParam).responseData { resp in
            switch resp.result {
            case .success(let data):
                do {
                    //只要符合String.Encoding.utf8这种编码的data都能转化成功,确认是返回数据结构是否正常
//                    let jsonString = NSString(data: data, encoding: String.Encoding.utf8.rawValue)
                    let asJSON = try JSONSerialization.jsonObject(with: data)
                    if let dic = asJSON as? NSDictionary{
                        if let successFlag = dic.object(forKey: "result") as? Bool,successFlag {//success
                            
                            let obj = dic.object(forKey: "data")
                            let json = JSON(obj!)
                            
                            self.returnBlock(json.rawString(),nil)
                            
                        }else{//error
                            var errMsg = ""
                            var errCode = ""
                            if let data = dic.object(forKey: "code") as? Int{
                                errCode = "\(data)"
                            }
                            if let msg = dic.object(forKey: "msg") as? String{
                                errMsg = msg
                            }
                            self.errorBlock(errCode,errMsg)
                            
                        }
                    }else{
                        self.errorBlock("", "response.value is not dictionary of \(APIConfig.UpdateSystemInfoAPI)")
                    }
                } catch (let error){
                    let errorMsg = APPConfig.isTestFlag ? ("Convert data to JSON failed: " + urlStr + "\n params: \(RequestConstant.AuthTokenParam)") : error.localizedDescription
                    self.errorBlock?("",errorMsg)
                    // Here, I like to keep a track of error if it occurs, and also print the response data if possible into String with UTF8 encoding
                    // I can't imagine the number of questions on SO where the error is because the API response simply not being a JSON and we end up asking for that "print", so be sure of it
//                    print("Error while decoding response: "\(error)" from: \(String(data: data, encoding: .utf8))")
                }
            case .failure(_):
                self.errorBlock?("",RequestErrorType.NetworkError.rawValue)
            }
        }
    }
    //2022-04-01之后安装的Job新协议用合并的上传
    func uploadSignaturesForNewStcForm(_ model: SignatureInfoModel){
        let urlStr = APIConfig.getRequestAPIForV2(APIConfig.UploadSignaturesAPI)
        netmanagerForUpload.upload(multipartFormData: {(formData) in
            //1.installer signature
            if let data = model.installer_sign_imagedata{
                let toData = Data(referencing: data)
                formData.append(toData, withName: "installer_signed_signature", fileName: SignatureType.Installer.rawValue + APPConfig.ImageSuffix, mimeType: "image/png")
            }
            if let data = model.installer_signed_at {
                formData.append(data.data(using: String.Encoding.utf8, allowLossyConversion: false)!, withName: "installer_signed_at")
            }
            //经纬度
            formData.append(model.installer_signature_latitude.data(using: String.Encoding.utf8, allowLossyConversion: false)!, withName: "installer_signature_latitude")
            formData.append(model.installer_signature_longitude.data(using: String.Encoding.utf8, allowLossyConversion: false)!, withName: "installer_signature_longitude")
            //installer签名自拍照
            if let data = model.installer_signature_selfie{
                formData.append(Data(referencing: data), withName: "installer_signature_selfie", fileName: "installer_signature_selfie" + APPConfig.ImageSuffix, mimeType: "image/png")
            }
            //installer的witness info
            if let data = model.installer_witness_signed_name{
                formData.append(data.data(using: String.Encoding.utf8, allowLossyConversion: false)!, withName: "installer_witness_signed_name")
            }
            if let data = model.installer_witness_signed_date{
                formData.append(data.data(using: String.Encoding.utf8, allowLossyConversion: false)!, withName: "installer_witness_signed_date")
            }
            if let data = model.installer_witness_signed_signature {
                formData.append(Data(referencing: data), withName: "installer_witness_signed_signature", fileName: "installer_witness_signed_signature" + APPConfig.ImageSuffix, mimeType: "image/png")
            }
            //2.designer
            if let data = model.designer_sign_imagedata{
                let toData = Data(referencing: data)
                formData.append(toData, withName: "designer_signed_signature", fileName: SignatureType.Designer.rawValue + APPConfig.ImageSuffix, mimeType: "image/png")
            }
            if let data = model.designer_signed_at {
                formData.append(data.data(using: String.Encoding.utf8, allowLossyConversion: false)!, withName: "designer_signed_at")
            }
            //designer的witness info
            if let data = model.designer_witness_signed_name{
                formData.append(data.data(using: String.Encoding.utf8, allowLossyConversion: false)!, withName: "designer_witness_signed_name")
            }
            if let data = model.designer_witness_signed_date{
                formData.append(data.data(using: String.Encoding.utf8, allowLossyConversion: false)!, withName: "designer_witness_signed_date")
            }
            if let data = model.designer_witness_signed_signature {
                formData.append(Data(referencing: data), withName: "designer_witness_signed_signature", fileName: "designer_witness_signed_signature" + APPConfig.ImageSuffix, mimeType: "image/png")
            }
            //3.owner签名
            if let data = model.owner_sign_imagedata{
                let toData = Data(referencing: data)
                formData.append(toData, withName: "owner_signed_signature", fileName: SignatureType.Owner.rawValue + APPConfig.ImageSuffix, mimeType: "image/png")
            }
            if let signedAt = model.owner_signed_at {
                formData.append(signedAt.data(using: String.Encoding.utf8, allowLossyConversion: false)!, withName: "owner_signed_at")
            }
            //
            if let printName = model.owner_signed_name {
                formData.append(printName.data(using: String.Encoding.utf8, allowLossyConversion: false)!, withName: "owner_signed_name")
            }
            //签名自拍照
            if let data = model.owner_signature_selfie{
                formData.append(Data(referencing: data), withName: "owner_signature_selfie", fileName: "owner_signature_selfie" + APPConfig.ImageSuffix, mimeType: "image/png")
            }
            
            //4.witness
            if let data = model.witness_sign_imagedata{
                let toData = Data(referencing: data)
                formData.append(toData, withName: "witness_signed_signature", fileName: SignatureType.Witness.rawValue + APPConfig.ImageSuffix, mimeType: "image/png")
            }
            if let printName = model.witness_signed_name {
                formData.append(printName.data(using: String.Encoding.utf8, allowLossyConversion: false)!, withName: "witness_signed_name")
            }
            if let signedAt = model.witness_signed_at {
                formData.append(signedAt.data(using: String.Encoding.utf8, allowLossyConversion: false)!, withName: "witness_signed_at")
            }
            
            //pvd id
            formData.append(model.pvd_id!.data(using: String.Encoding.utf8, allowLossyConversion: false)!, withName: "pvd_id")

            //1.协议赋值参数和交互参数
            for item in model.onlineStatementParams {
                let d = "\(item.value)"
                formData.append(d.data(using: String.Encoding.utf8, allowLossyConversion: false)!, withName: item.key)
            }
            //2.协议自拍照交互参数
            for item in model.onlineStatementPhotoParams {
                if let d = item.value as? NSData {
                    formData.append(Data(referencing: d), withName: item.key, fileName: item.key + APPConfig.ImageSuffix, mimeType: "image/png")
                }
            }
        }, to: urlStr, method: HTTPMethod.put, headers: RequestConstant.AuthTokenParam).responseData { resp in
            switch resp.result {
            case .success(let data):
                do {
                    //只要符合String.Encoding.utf8这种编码的data都能转化成功,确认是返回数据结构是否正常
//                    let jsonString = NSString(data: data, encoding: String.Encoding.utf8.rawValue)
                    let asJSON = try JSONSerialization.jsonObject(with: data)
                    if let dic = asJSON as? NSDictionary{
                        if let successFlag = dic.object(forKey: "result") as? Bool,successFlag {//success

                            let obj = dic.object(forKey: "data")
                            let json = JSON(obj!)

                            self.returnBlock(json.rawString(),nil)

                        }else{//error
                            var errMsg = ""
                            var errCode = ""
                            if let data = dic.object(forKey: "code") as? Int{
                                errCode = "\(data)"
                            }
                            if let msg = dic.object(forKey: "msg") as? String{
                                errMsg = msg
                            }
                            self.errorBlock(errCode,errMsg)

                        }
                    }else{
                        self.errorBlock("", "response.value is not dictionary of \(APIConfig.UploadSignaturesAPI)")
                    }
                } catch (let error){
                    let errorMsg = APPConfig.isTestFlag ? ("Convert data to JSON failed: " + urlStr + "\n params: \(RequestConstant.AuthTokenParam)") : error.localizedDescription
                    self.errorBlock?("",errorMsg)
                    // Here, I like to keep a track of error if it occurs, and also print the response data if possible into String with UTF8 encoding
                    // I can't imagine the number of questions on SO where the error is because the API response simply not being a JSON and we end up asking for that "print", so be sure of it
//                    print("Error while decoding response: "\(error)" from: \(String(data: data, encoding: .utf8))")
                }
            case .failure( _ ):
                self.errorBlock?("",RequestErrorType.NetworkError.rawValue)
            }
        }
    }
    //MARK: - 上传panelnumber
    func uploadSerialsNumber(_ panelModel: PanelNumberImageDBModel, type: ScanningType){
        var apiStr = ""
        switch type{
        case .panel:
            apiStr = APIConfig.UploadPanelNumbersAPI
        case .inverter:
            apiStr = APIConfig.UploadInverterNumbersAPI
        case .tank:
            apiStr = APIConfig.UploadTankNumbersAPI
        }
        let urlStr = APIConfig.getRequestAPIForV2(apiStr)
        netmanagerForUpload.upload(multipartFormData: {(formData) in
            var localPanelNumbers = [PanelNumberImageDBModel]()
            let uploadModel = PanelNumberImageDBModel()
            let operType = panelModel.operType
            if operType == DataOperType.Add.rawValue  {
                let realPath = FileUtil().getRealFilePath(panelModel.image)
                let url = URL(fileURLWithPath: realPath)
                let fileName = url.deletingPathExtension().lastPathComponent
                formData.append(url, withName: "serial_number_file", fileName: fileName + APPConfig.ImageSuffix, mimeType: "image/png")
                
                uploadModel.original_code = panelModel.original_code
                uploadModel.auto_scan = panelModel.auto_scan
                uploadModel.scan_type = panelModel.scan_type
                uploadModel.pvd_id = panelModel.pvd_id
                uploadModel.code = panelModel.code
                uploadModel.latitude = panelModel.latitude//Double(108.1234567)
                uploadModel.longitude = panelModel.longitude//Double(80.1234567)
                uploadModel.record_at = panelModel.record_at
                uploadModel.barcode_type = panelModel.barcode_type
                uploadModel.confidence = panelModel.confidence
                if panelModel.auto_scan == 1{//扫描识别的code，才有scan time和confidence
                    uploadModel.scan_timespan = panelModel.scan_timespan
                }
            }
            if operType == DataOperType.Del.rawValue {
                uploadModel.id = panelModel.id
                uploadModel.removed = 1
                
            }
            if operType == DataOperType.Modify.rawValue {
                uploadModel.pvd_id = panelModel.pvd_id
                uploadModel.id = panelModel.id
                uploadModel.code = panelModel.code
                uploadModel.latitude = panelModel.latitude//Double(108.1234567)
                uploadModel.longitude = panelModel.longitude//Double(80.1234567)
                uploadModel.auto_scan = panelModel.auto_scan
                uploadModel.scan_type = panelModel.scan_type
                uploadModel.barcode_type = panelModel.barcode_type
                uploadModel.record_at = panelModel.record_at
            }
            localPanelNumbers.append(uploadModel)
            //pvd id
            formData.append(panelModel.pvd_id.data(using: String.Encoding.utf8, allowLossyConversion: false)!, withName: "pvd_id")
            
            let data = try!  JSONSerialization.data(withJSONObject: localPanelNumbers.toJSON(), options: JSONSerialization.WritingOptions.prettyPrinted)
            
            formData.append(data, withName: "serial_numbers")
            
            
        }, to: urlStr, method: HTTPMethod.put, headers: RequestConstant.AuthTokenParam).responseData { resp in
            switch resp.result {
            case .success(let data):
                do {
                    //只要符合String.Encoding.utf8这种编码的data都能转化成功,确认是返回数据结构是否正常
//                    let jsonString = NSString(data: data, encoding: String.Encoding.utf8.rawValue)
                    let asJSON = try JSONSerialization.jsonObject(with: data)
                    if let dic = asJSON as? NSDictionary{
                        if let successFlag = dic.object(forKey: "result") as? Bool,successFlag {//success
                            let obj = dic.object(forKey: "data")
                            let json = JSON(obj!)
                            
                            self.returnBlock(json.rawString(),nil)
                            
                        }else{//error
                            var errMsg = ""
                            var errCode = ""
                            if let data = dic.object(forKey: "code") as? Int{
                                errCode = "\(data)"
                            }
                            if let msg = dic.object(forKey: "msg") as? String{
                                errMsg = msg
                            }
                            self.errorBlock(errCode,errMsg)
                            
                        }
                    }else{
                        self.errorBlock("", "response.value is not dictionary of \(apiStr)")
                    }
                } catch (let error){
                    let errorMsg = APPConfig.isTestFlag ? ("Convert data to JSON failed: " + urlStr + "\n params: \(RequestConstant.AuthTokenParam)") : error.localizedDescription
                    self.errorBlock?("",errorMsg)
                }
            case .failure(_):
                self.errorBlock?("",RequestErrorType.NetworkError.rawValue)
            }
        }
    }
    //MARK: -  上传 bool and text data（pvd， service共用，）
    func uploadChecklistBoolOrText(checklistModel: PVDChecklistModel, jobType: JobType = .pvdJob){
        let urlStr = APIConfig.getRequestAPIForV2(jobType == .pvdJob ? APIConfig.UploadCheckListInfoAPI : APIConfig.UploadServiceJobCheckListAPI)
        netmanagerForUpload.upload(multipartFormData: { (formData) in
            var localCheckList = [PVDChecklistModel]()
            localCheckList.append(checklistModel)
            
            //pvd Job的 id是pvd_id, service job的key是id
            let idKeyName = jobType == .pvdJob ? "pvd_id" : "id"
            formData.append(checklistModel.pvdId.data(using: String.Encoding.utf8, allowLossyConversion: false)!, withName: idKeyName)
            
            let data = try!  JSONSerialization.data(withJSONObject: localCheckList.toJSON(), options: JSONSerialization.WritingOptions.prettyPrinted)
            
            formData.append(data, withName: "checklists")
            
        }, to: urlStr, method: HTTPMethod.post, headers: RequestConstant.AuthTokenParam).responseData {resp in
            switch resp.result {
            case .success(let data):
                do {
                    //只要符合String.Encoding.utf8这种编码的data都能转化成功,确认是返回数据结构是否正常
//                    let jsonString = NSString(data: data, encoding: String.Encoding.utf8.rawValue)
                    let asJSON = try JSONSerialization.jsonObject(with: data)
                    if let dic = asJSON as? NSDictionary{
                        if let successFlag = dic.object(forKey: "result") as? Bool,successFlag {//success
                            let obj = dic.object(forKey: "data")
                            let json = JSON(obj!)
                            
                            self.returnBlock(json.rawString(),nil)
                            
                        }else{//error
                            
                            let msg = dic.object(forKey: "msg") as! String
                            self.errorBlock("",msg)
                            
                        }
                    }else{
                        self.errorBlock("", "response.value is not dictionary of \(jobType == .pvdJob ? APIConfig.UploadCheckListInfoAPI : APIConfig.UploadServiceJobCheckListAPI)")
                    }
                } catch (let error){
                    let errorMsg = APPConfig.isTestFlag ? ("Convert data to JSON failed: " + urlStr + "\n params: \(RequestConstant.AuthTokenParam)") : error.localizedDescription
                    self.errorBlock?("",errorMsg)
                }
            case .failure(_):
                self.errorBlock?("",RequestErrorType.NetworkError.rawValue)
            }
        }
    }
    //MARK: - 上传image类型的图片或pdf文件
    func uploadChecklistImage(imageModel: CheckListImageDBModel, jobType: JobType = .pvdJob){
        let urlStr = APIConfig.getRequestAPIForV2(jobType == .pvdJob ? APIConfig.UploadCheckListInfoAPI : APIConfig.UploadServiceJobCheckListAPI)
        netmanagerForUpload.upload(multipartFormData: { (formData) in
            var localCheckList = [PVDChecklistModel]()
            let tempCheckModel = PVDChecklistModel()
            tempCheckModel.id = imageModel.checklist_id
            tempCheckModel.type = ChecklistType.Image.rawValue
            if imageModel.oper_type == DataOperType.Add.rawValue {
                tempCheckModel.answered_at = DateUtil().getCurrentDatetime()
                tempCheckModel.full_name = APPConfig.loginInfo.fullName
                
                let imagePath = imageModel.image
                let fileName = "\(imageModel.id)"
                let realPath = FileUtil().getRealFilePath(imagePath)
                if realPath.hasSuffix(APPConfig.PDFSuffix) {//包含pdf后缀
                    formData.append(URL(fileURLWithPath: realPath), withName: fileName, fileName: fileName + APPConfig.PDFSuffix, mimeType: "application/pdf")
                }else{
                    formData.append(URL(fileURLWithPath: realPath), withName: fileName, fileName: fileName + APPConfig.ImageSuffix, mimeType: "image/png")
                }
                let tempImageModel = CheckListImageDBModel()
                tempImageModel.id = fileName
                tempImageModel.record_at = imageModel.record_at
                tempImageModel.photo_source = imageModel.photo_source
                tempImageModel.photo_created_at = imageModel.photo_created_at
                tempImageModel.longitude = imageModel.longitude
                tempImageModel.latitude = imageModel.latitude
                tempCheckModel.images.append(tempImageModel)

            }else if imageModel.oper_type == DataOperType.Del.rawValue {
                imageModel.record_at = ""
                tempCheckModel.images.append(imageModel)
            }

            localCheckList.append(tempCheckModel)
            //pvd id
            let idKeyName = jobType == .pvdJob ? "pvd_id" : "id"
            formData.append(imageModel.pvd_id.data(using: String.Encoding.utf8, allowLossyConversion: false)!, withName: idKeyName)
            
            if let data = try?  JSONSerialization.data(withJSONObject: localCheckList.toJSON(), options: JSONSerialization.WritingOptions.prettyPrinted){
                formData.append(data, withName: "checklists")
            }
        }, to: urlStr, method: HTTPMethod.post, headers: RequestConstant.AuthTokenParam).responseData {resp in
            switch resp.result {
            case .success(let data):
                do {
                    //只要符合String.Encoding.utf8这种编码的data都能转化成功,确认是返回数据结构是否正常
//                    let jsonString = NSString(data: data, encoding: String.Encoding.utf8.rawValue)
                    let asJSON = try JSONSerialization.jsonObject(with: data)
                    if let dic = asJSON as? NSDictionary{
                        if let successFlag = dic.object(forKey: "result") as? Bool,successFlag {//success
                            if let obj = dic.object(forKey: "data"){
                                let json = JSON(obj)
                                self.returnBlock(json.rawString(), nil)
                            }
                            
                        }else{//error
                            var errMsg = ""
                            var errCode = ""
                            if let data = dic.object(forKey: "code") as? Int{
                                errCode = "\(data)"
                            }
                            if let msg = dic.object(forKey: "msg") as? String{
                                errMsg = msg
                            }
                            self.errorBlock(errCode,errMsg)
                            
                        }
                    }else{
                        self.errorBlock("", "response.value is not dictionary of \(jobType == .pvdJob ? APIConfig.UploadCheckListInfoAPI : APIConfig.UploadServiceJobCheckListAPI)")
                    }
                } catch (let error){
                    let errorMsg = APPConfig.isTestFlag ? ("Convert data to JSON failed: " + urlStr + "\n params: \(RequestConstant.AuthTokenParam)") : error.localizedDescription
                    self.errorBlock?("",errorMsg)
                    // Here, I like to keep a track of error if it occurs, and also print the response data if possible into String with UTF8 encoding
                    // I can't imagine the number of questions on SO where the error is because the API response simply not being a JSON and we end up asking for that "print", so be sure of it
//                    print("Error while decoding response: "\(error)" from: \(String(data: data, encoding: .utf8))")
                }
            case .failure(_):
                self.errorBlock?("",RequestErrorType.NetworkError.rawValue)
            }
        }
    }
    //MARK: - 上传附件，包括NOC，Other
    func uploadAttachment(_ imageModel: CheckListImageDBModel){
        let urlStr = APIConfig.getRequestAPIForV2(APIConfig.UploadAttachmentAPI)
        netmanagerForUpload.upload(multipartFormData: {(formData) in
            let fileName = DateUtil().getCurrentDatetimeTamp()
            //coc attachment
            //上传类型
            var attachmentTypeName = "notice_of_completion"
            if imageModel.checklist_id == ChecklistFixedId.otherAttachment.rawValue {
                attachmentTypeName = "other"
            }
            if imageModel.image.hasSuffix(APPConfig.PDFSuffix) {//包含pdf后缀
                formData.append(URL(fileURLWithPath: imageModel.image), withName: attachmentTypeName, fileName: fileName + APPConfig.PDFSuffix, mimeType: "application/pdf")
            }else{
                formData.append(URL(fileURLWithPath: imageModel.image), withName: attachmentTypeName, fileName: fileName + APPConfig.ImageSuffix, mimeType: "image/png")
            }
            
            formData.append(attachmentTypeName.data(using: String.Encoding.utf8, allowLossyConversion: false)!, withName: "type")
            //pvd id
            formData.append(JobDetailModelHelper.shared.jobDetailModel.id.data(using: String.Encoding.utf8, allowLossyConversion: false)!, withName: "pvd_id")//pvd id
            
        }, to: urlStr, method: HTTPMethod.post, headers: RequestConstant.AuthTokenParam).responseData {resp in
            switch resp.result {
            case .success(let data):
                do {
                    //只要符合String.Encoding.utf8这种编码的data都能转化成功,确认是返回数据结构是否正常
//                    let jsonString = NSString(data: data, encoding: String.Encoding.utf8.rawValue)
                    let asJSON = try JSONSerialization.jsonObject(with: data)
                    if let dic = asJSON as? NSDictionary{
                        if let successFlag = dic.object(forKey: "result") as? Bool,successFlag {//success
                            if let obj = dic.object(forKey: "data"){
                                let json = JSON(obj)
                                self.returnBlock(json.rawString(),nil)
                            }
                        }else{//error
                            var errMsg = ""
                            var errCode = ""
                            if let data = dic.object(forKey: "code") as? Int{
                                errCode = "\(data)"
                            }
                            if let msg = dic.object(forKey: "msg") as? String{
                                errMsg = msg
                            }
                            self.errorBlock(errCode,errMsg)
                            
                        }
                    }else{
                        self.errorBlock("", "response.value is not dictionary of \(APIConfig.UploadAttachmentAPI)")
                    }
                } catch (let error){
                    let errorMsg = APPConfig.isTestFlag ? ("Convert data to JSON failed: " + urlStr + "\n params: \(RequestConstant.AuthTokenParam)") : error.localizedDescription
                    self.errorBlock?("",errorMsg)
                }
            case .failure(_):
                self.errorBlock?("",RequestErrorType.NetworkError.rawValue)
            }
        }
    }
    //MARK: - 删除附件，包括NOC，Other
    func deleteAttachment(_ imageModel: CheckListImageDBModel){
        let attachmentType = (imageModel.checklist_id == ChecklistFixedId.nocAttachment.rawValue ? "notice_of_completion" : "other")
        
        let params: Parameters = ["pvd_id":JobDetailModelHelper.shared.jobDetailModel.pvd_id,
                                  "type": attachmentType,
                                  "attachment_id": imageModel.id]
        
        let alRequest = ALRequest.init(mainURL: APIConfig.getRequestAPIForV2(APIConfig.DeleteAttachmentAPI), method: .post, headers: RequestConstant.AuthTokenParam, paramDict: params, successBlock: { (obj, _) -> Void in
            
            let json = JSON(obj!)
            let modeStr = json.rawString()
            
            let model = JSONDeserializer<PVDDetailModel>.deserializeFrom(json: modeStr)
            
            self.returnBlock(model,nil)
            
        }) {(code, obj) -> Void in
            self.errorBlock?(code, obj)
        }
        alRequest.startRequest()
    }
    //MARK: - finish Job
    func finishJob(_ location: String){
        
        let params: Parameters = ["id":JobDetailModelHelper.shared.jobDetailModel.pvd_id,"location": location]
        
        let alRequest = ALRequest.init(mainURL: APIConfig.getRequestAPIForV2(APIConfig.FinishJobAPI), method: .put, headers: RequestConstant.AuthTokenParam, paramDict: params, successBlock: { (obj, _) -> Void in
            
            let json = JSON(obj!)
            let modeStr = json.rawString()
            
            let model = JSONDeserializer<PVDDetailModel>.deserializeFrom(json: modeStr)
            
            self.returnBlock(model,nil)
            
        }) {(code, obj) -> Void in
            self.errorBlock?(code, obj)
        }
        alRequest.startRequest()
    }
    //MARK: - reopen Job
    func reopenJob(){
        
        let alRequest = ALRequest.init(mainURL: APIConfig.getRequestAPIForV2(APIConfig.ReopenJobAPI,id: JobDetailModelHelper.shared.jobDetailModel.id), method: .put, headers: RequestConstant.AuthTokenParam, paramDict: nil, successBlock: { (obj, _) -> Void in
            
            let json = JSON(obj!)
            let modeStr = json.rawString()
            
            let model = JSONDeserializer<PVDDetailModel>.deserializeFrom(json: modeStr)
            
            self.returnBlock(model,nil)
            
        }) {(code, obj) -> Void in
            self.errorBlock?(code, obj)
        }
        alRequest.startRequest()
    }
    
    //MARK: - panel install时验证
    func panelInstalledValidate(_ locationModel: LocationModel,dateOfCompletion: String){
        
        let params: Parameters = ["id": JobDetailModelHelper.shared.jobDetailModel.pvd_id, "latitude": locationModel.latitude as Any, "longitude": locationModel.longitude as Any, "install_date": dateOfCompletion]
        
        let alRequest = ALRequest.init(mainURL: APIConfig.getRequestAPIForV2(APIConfig.PanelInstallValidateAPI), method: .post, headers: RequestConstant.AuthTokenParam, paramDict: params, successBlock: { (obj, _) -> Void in
            
            let json = JSON(obj!)
            let modeStr = json.rawString()
            
            let model = JSONDeserializer<PVDDetailModel>.deserializeFrom(json: modeStr)
            
            self.returnBlock(model,nil)
            
        }) {(code, obj) -> Void in
            self.errorBlock?(code, obj)
        }
        alRequest.startRequest()
    }
    //MARK: - 编辑安装地址信息
    func changeInstallationAddress(_ viewModel: CreateJobInstallAddressViewModel){
        var params: Parameters = Parameters()
        params["id"] = JobDetailModelHelper.shared.jobDetailModel.pvd_id
        //Install address
        params["unit_type"] = viewModel.installAddress.unit_type
        params["unit_number"] = viewModel.installAddress.unit_number
        params["street_number"] = viewModel.installAddress.street_number
        params["street_name"] = viewModel.installAddress.street_name
        params["street_type"] = viewModel.installAddress.street_type
        params["suburb"] = viewModel.installAddress.suburb
        params["state"] = viewModel.installAddress.state
        params["post_code"] = viewModel.installAddress.post_code
        params["address_text"] = viewModel.installAddress.final_full_address
        params["address_id"] = viewModel.installAddress.address_id
        
        //add specail address
        if viewModel.addSpecialAddressFlag {
            params["special_address"] = viewModel.specialAddress
        }
        //owner address
        params["same_as_postal"] = viewModel.sameAsPostalAddress ? "true" : "false"
        //same as postall address
        if viewModel.sameAsPostalAddress {
            params["owner_address_type"] = AddressType.physical.rawValue
            params["address_id"] = viewModel.installAddress.address_id
            params["owner_address_text"] = viewModel.installAddress.final_full_address
            params["owner_unit_type"] = viewModel.installAddress.unit_type
            params["owner_unit_number"] = viewModel.installAddress.unit_number
            params["owner_street_number"] = viewModel.installAddress.street_number
            params["owner_street_name"] = viewModel.installAddress.street_name
            params["owner_street_type"] = viewModel.installAddress.street_type
            params["owner_suburb"] = viewModel.installAddress.suburb
            params["owner_state"] = viewModel.installAddress.state
            params["owner_post_code"] = viewModel.installAddress.post_code
        }else{//
            params["owner_address_type"] = viewModel.postalAddress.address_type.rawValue
            if viewModel.postalAddress.address_type == .physical {//physical
                params["owner_address_text"] = viewModel.postalAddress.physicalAddress.final_full_address
                params["owner_unit_type"] = viewModel.postalAddress.physicalAddress.unit_type
                params["owner_unit_number"] = viewModel.postalAddress.physicalAddress.unit_number
                params["owner_street_number"] = viewModel.postalAddress.physicalAddress.street_number
                params["owner_street_name"] = viewModel.postalAddress.physicalAddress.street_name
                params["owner_street_type"] = viewModel.postalAddress.physicalAddress.street_type
                params["owner_suburb"] = viewModel.postalAddress.physicalAddress.suburb
                params["owner_state"] = viewModel.postalAddress.physicalAddress.state
                params["owner_post_code"] = viewModel.installAddress.post_code
            }else if viewModel.postalAddress.address_type == .poBox{//po box
                params["owner_delivery_type"] = viewModel.postalAddress.delivery_type
                params["owner_delivery_number"] = viewModel.postalAddress.delivery_number
                params["owner_suburb"] = viewModel.postalAddress.suburb
                params["owner_state"] = viewModel.postalAddress.state
                params["owner_post_code"] = viewModel.postalAddress.post_code
            }
        }
        //获取Post字符串
        Tool().printPostJSONString(params)
        let alRequest = ALRequest.init(mainURL: APIConfig.getRequestAPIForV2(APIConfig.ChangeInstallationAddressAPI), method: .put, headers: RequestConstant.AuthTokenParam, paramDict: params, successBlock: { (obj, _) -> Void in
            
            let json = JSON(obj!)
            let modeStr = json.rawString()
            
            let model = JSONDeserializer<PVDDetailModel>.deserializeFrom(json: modeStr)
            
            self.returnBlock(model,nil)
            
        }) {(code, obj) -> Void in
            self.errorBlock?(code, obj)
        }
        alRequest.startRequest()
    }
    //MARK: - 签名时给owner发送签名链接信息
    func sendSMSToOwner(_ ownerName:String,phoneNumber: String){
        
        let params: Parameters = ["id": JobDetailModelHelper.shared.jobDetailModel.pvd_id, "owner_name": ownerName, "owner_phone": phoneNumber]
        
        let alRequest = ALRequest.init(mainURL: APIConfig.getRequestAPIForV2(APIConfig.SendSMSToOwner), method: .put, headers: RequestConstant.AuthTokenParam, paramDict: params, successBlock: { (obj, _) -> Void in
            
            self.returnBlock(nil,nil)
            
        }) {(code, obj) -> Void in
            self.errorBlock?(code, obj)
        }
        alRequest.startRequest()
    }
    //MARK: - 签名时给owner发送email链接信息
    func sendEmailToOwner(_ ownerName:String,email: String){
        
        let params: Parameters = ["id": JobDetailModelHelper.shared.jobDetailModel.pvd_id, "owner_name": ownerName, "owner_email": email]
        
        let alRequest = ALRequest.init(mainURL: APIConfig.getRequestAPIForV2(APIConfig.SendEmailToOwner), method: .put, headers: RequestConstant.AuthTokenParam, paramDict: params, successBlock: { (obj, _) -> Void in
            
            self.returnBlock(nil,nil)
            
        }) {(code, obj) -> Void in
            self.errorBlock?(code, obj)
        }
        alRequest.startRequest()
    }
    func submitAPPComment(_ model: AppCommentModel){
        var params: Parameters!
        guard let rateId = model.id else {
            return
        }
        if model.ignoreFlag {//用户点击了not now，忽略评分
            params = ["ignored": true]
        }else{//submit 评分
            params = ["rating": model.rating,"comment": model.comment]
        }
        
        let alRequest = ALRequest.init(mainURL: APIConfig.getRequestAPIForV2(APIConfig.AppCommentAPI,id: "\(rateId)"), method: .patch, headers: RequestConstant.AuthTokenParam, paramDict: params, successBlock: { (code, obj) -> Void in
            
            self.returnBlock(nil,nil)
            
        }) {(code, obj) -> Void in
            self.errorBlock?(code, obj)
        }
        alRequest.startRequest()
    }
    func readResignStatementMsg(){
        let params: Parameters = ["pvd_id": JobDetailModelHelper.shared.jobDetailModel.id]
        let alRequest = ALRequest.init(mainURL: APIConfig.getRequestAPIForV2(APIConfig.ReadResignStatementMsgAPI), method: .post, headers: RequestConstant.AuthTokenParam, paramDict: params, successBlock: {(obj, _) -> Void in
            let json = JSON(obj!)
            let modeStr = json.rawString()
            let model = JSONDeserializer<PVDDetailModel>.deserializeFrom(json: modeStr)
            
            self.returnBlock(model,nil)
            
        }) {(code, obj) -> Void in
            self.errorBlock?(code, obj)
        }
        alRequest.startRequest()
    }
}
